﻿using System;
using System.Collections.Generic;
using System.Text;

namespace ChEngine
{
    public class Divide
    {
        IBitBoard board;
        IMoveGenerator generator;
        int[] moves = new int[1000];
        public Divide(IBitBoard board, IMoveGenerator generator)
        {
            this.board = board;
            this.generator = generator;
        }
        public event EventHandler DividePartialResult;
        public BitMove CurrentMove { get; set; }
        public ulong CurrentNodesCount { get; set; }
        public DivideResults DoDivide(int depth)
        {
            DivideResults div = new DivideResults();
            div.MovesCount = generator.GetMoves(board, moves, 0, MoveGenerationMode.All);
            for (int i = 0; i < div.MovesCount; ++i)
            {
                if (generator.IsMoveLegal(board, moves[i]))
                {
                    Side moving = board.ToMove;
                    board.DoMove(moves[i]);
                    if (generator.InCheck(board, moving))
                    {
                        board.UndoMove(moves[i]);
                        continue;
                    }
                    Perft perft = new Perft(board, generator);
                    PerfResults pres  = perft.DoPerft(depth - 1);
                    div.NodesCount += pres.MovesCount;
                    CurrentNodesCount = pres.MovesCount;
                    CurrentMove = BitMove.FromRaw(moves[i], board);
                    if (null != DividePartialResult)
                        DividePartialResult(this, EventArgs.Empty);
                    board.UndoMove(moves[i]);
                }
            }

            return div;
        }
    }
}
